//
//  Project_Step5ViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/22.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Project_Step7ViewController.h"
#import "Project_Step6ViewController.h"
#import "Project_Step8ViewController.h"
#import "BottomActionView.h"
#import "MachinePriceData.h"
#import "MachinePriceDataResp.h"
#import "SystemConfigTableViewCell.h"
#import "Project_TabViewController.h"
#import "DefaultStyleTableViewCell.h"
#import "Project_Step6ViewController.h"
#import <CustomIOSAlertView.h>
#import "ProjectData.h"
#import "ProjectManager.h"
#import "CommonResponse.h"
#import <MBProgressHUD.h>


@interface Project_Step7ViewController () {
    int value1;
    int value2;
    int value3;
    MBProgressHUD *HUD;
    BOOL priceModified;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomActionView *footerView;
@property (nonatomic,strong) UITextField *priceTextField;
@property (nonatomic,strong) ProjectData *projectData;

@end

@implementation Project_Step7ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self loadData];
    
}

/**
 *  初始化数据
 */
- (void)initData {
    self.projectData = [[ProjectManager manager]project];
}

#pragma mark - 加载数据
/**
 *  获取报价信息
 */
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_BY_GUID token:[[AccountManager manager]token] paramDic:param resultClass:[ProjectData class] success:^(ProjectData *obj) {
        self.projectData.fuCaiPrice = obj.getProjectResult.fuCaiPrice;
        self.projectData.taxRate = obj.getProjectResult.taxRate;
        self.projectData.totalPrice = obj.getProjectResult.totalPrice;
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        CMLog(@"获取数据错误：%@", error);
    }];
}



- (void)savePriceData:(NSString*)price forTag:(NSInteger)tag {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSDictionary *project = [self.projectData keyValues];
    
    
    if (tag == 0) {
        //辅材
        [project setValue:price forKey:@"fuCaiPrice"];
    }
    else if (tag == 1){
        //税率
        [project setValue:[NSString stringWithFormat:@"%f", [price doubleValue]/100] forKey:@"taxRate"];
    }
    else {
        //成交价
        [project setValue:price forKey:@"transPrice"];
    }
    
    [project setValue:[NSNumber numberWithInt:1] forKey:@"phase"];
    [params setObject:project forKey:@"prjInfo"];
  
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"价格提交中...";
    
    NSData *jsonData = [params JSONString];
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"json data:%@",json);
    
    [HttpClient postWithUrl:HTTP_POST_PROJECT_INFO token:[[AccountManager manager] token] paramDic:params resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        //需要重新拉取项目数据，来更新总报价数据
        
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        [Tools showMessageCenter:@"修改失败，请重试！"];
        CMLog(@"错误信息为：%@",error);
    }];
}

- (void)loadProjectInfoByGuid:(NSString*)guid{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:guid forKey:@"pid"];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_BY_GUID token:[[AccountManager manager]token] paramDic:param resultClass:[ProjectData class] success:^(ProjectData *obj) {
        [HUD setHidden:YES];
        self.projectData.totalPrice = obj.getProjectResult.totalPrice;
        [[ProjectManager manager]project].totalPrice = obj.getProjectResult.totalPrice;
        
        self.projectData.fuCaiPrice = obj.getProjectResult.fuCaiPrice;
        [[ProjectManager manager]project].fuCaiPrice = obj.getProjectResult.fuCaiPrice;
        
        self.projectData.taxRate = obj.getProjectResult.taxRate;
        [[ProjectManager manager]project].taxRate = obj.getProjectResult.taxRate;
        
        self.projectData.transPrice = obj.getProjectResult.transPrice;
        [[ProjectManager manager]project].transPrice = obj.getProjectResult.transPrice;
        
        [[ProjectManager manager]saveProject:self.projectData];
        
        [self.tableView reloadData];
        [Tools showMessageCenter:@"修改成功！"];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        [Tools showMessageCenter:@"修改失败，请重试！"];
        CMLog(@"获取数据错误：%@", error);
    }];
}



#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"其他报价";
    
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //底部的上一步，下一步按钮
    self.footerView = [[BottomActionView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    __block Project_Step7ViewController *tmp = (Project_Step7ViewController*)self;
    [self.footerView addLeftBtnBlock:^(id obj) {
        //TODO
        [[ProjectManager manager]goLastPage];
        [tmp.navigationController popViewControllerAnimated:YES];
        
    }];
    [self.footerView addRightBtnBlock:^(id obj) {
        Project_Step8ViewController *view = [Project_Step8ViewController new];
        [tmp.navigationController pushViewController:view animated:YES];
    }];
    [self.footerView setLeftBtnTitle:@"上一步" andRightBtnTitle:@"下一步" andCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
    [self.view addSubview:self.footerView];
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, self.view.height - kNavigation_Bar_Height - kStatus_Bar_Height - KAction_Bar_Height) style:UITableViewStylePlain];
    self.tableView.backgroundView = [[UIView alloc]init];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

#pragma mark - 事件响应
/**
 *  直接跳转到项目页面
 */
-(void)onBackToProject {
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[Project_TabViewController class]]) {
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //报价
    static NSString *identifier2 = @"priceCell";
    DefaultStyleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier2];
    if (cell == nil) {
        cell = [[DefaultStyleTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier2];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"辅材&人工";
        
        NSString *detail = [NSString stringWithFormat:@"%.2f元", self.projectData.fuCaiPrice];
        cell.detailTextLabel.text = detail;
    }
    else if (indexPath.row == 1){
        cell.textLabel.text = @"税率";
        
        NSString *detail = [NSString stringWithFormat:@"%.2f%%", self.projectData.taxRate*100];
        cell.detailTextLabel.text = detail;
    }
    else {
        cell.textLabel.text = @"成交价";
        
        NSString *detail = [NSString stringWithFormat:@"%.2f", self.projectData.transPrice];
        cell.detailTextLabel.text = detail;
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        [self editPrice:@"辅材&人工" andPrice:self.projectData.fuCaiPrice andRow:indexPath.row];
        //辅材
    }
    else if (indexPath.row == 1){
        //税率
        [self editPrice:@"税率" andPrice:self.projectData.taxRate*100 andRow:indexPath.row];
    }
    else {
        //成交价
        [self editPrice:@"成交价" andPrice:self.projectData.transPrice andRow:indexPath.row];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CELL_HEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 50)];
    footerView.backgroundColor = [UIColor whiteColor];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 1)];
    lineView.backgroundColor = [UIColor grayColor];
    [footerView addSubview:lineView];
    
    NSString *costStr = [NSString stringWithFormat:@"总价：%.2f元", self.projectData.totalPrice];
    UILabel *totalLabel = [UILabel labelSingleLineFontSize:kListTitleFontSize content:costStr];
    totalLabel.centerX = footerView.width/2;
    totalLabel.centerY = footerView.height/2;
    totalLabel.textColor = [UIColor redColor];
    [footerView addSubview:totalLabel];
    
    return footerView;
}

-(void)editPrice:(NSString*) machineName andPrice:(double)price andRow: (NSInteger)row{
    CustomIOSAlertView *alert = [[CustomIOSAlertView alloc] init];
    [alert setUseMotionEffects:YES];
    alert.tag = row;
    
    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width-50, 200)];
    
    //标题栏
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, subView.width, 50)];
    [titleView setUserInteractionEnabled:YES];
    
    titleView.backgroundColor = CM_ACTION_CELL_COLOR;
    [subView addSubview:titleView];
    //左上角、右上角圆角为7
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:titleView.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(7, 7)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = titleView.bounds;
    maskLayer.path = maskPath.CGPath;
    titleView.layer.mask = maskLayer;
    
    //添加文字
    UILabel *titleLabel = [UILabel labelSingleLineFontSize:14 content:[NSString stringWithFormat:@"%@报价信息", machineName]];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.centerY = titleView.centerY;
    titleLabel.centerX = titleView.centerX;
    [titleView addSubview:titleLabel];
    
    //此次报价
    UILabel *curLabel = [UILabel labelSingleLineFontSize:14 content:@"税率(%)："];
    if (row == 1) {
        curLabel.text = @"税率(%)：";
    }
    else {
        curLabel.text = @"价格：";
    }
    curLabel.x = 20;
    curLabel.y = CGRectGetMaxY(titleView.frame)+70;
    curLabel.textAlignment = NSTextAlignmentLeft;
    [subView addSubview:curLabel];
    
    self.priceTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(curLabel.frame), curLabel.y, subView.width/2, curLabel.height)];
    self.priceTextField.textColor = CM_TABLE_DETAIL_COLOR;
    self.priceTextField.font = [UIFont systemFontOfSize:kListTitleFontSize];
    if (row == 1) {
        self.priceTextField.placeholder = [NSString stringWithFormat:@"%0.2f", price];
    }
    else {
        self.priceTextField.placeholder = [NSString stringWithFormat:@"%.2f元", price];
    }
    self.priceTextField.keyboardType=UIKeyboardTypeDecimalPad;//设置键盘类型为数字的
    self.priceTextField.returnKeyType=UIReturnKeyDefault;//返回键的类型
    [self.priceTextField addTarget:self action:@selector(textFieldChange) forControlEvents:UIControlEventEditingChanged];
    [subView addSubview:self.priceTextField];
    //    [self.priceTextField addTarget:self action:@selector(textFieldChange) forControlEvents:UIControlEventEditingChanged];
    
    
    
    [alert setContainerView:subView];
    [alert setButtonTitles:@[@"确定", @"取消"]];
    [alert setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex) {
            case 1:
                
                break;
            case 0:
            {
                if (priceModified && self.priceTextField.text.length > 0) {
                    NSString *editPrice = self.priceTextField.text;
                    [self savePriceData:editPrice forTag:alertView.tag];
                }
            }
                break;
            default:
                break;
        }
    }];
    
    [alert show];
    
}

- (void)textFieldChange {
    priceModified = YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
